﻿using Futajma.MigrationStudio.GenericImporter;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Futajma.MigrationStudio.GenericImporter
{
    [ObfuscationAttribute(Exclude = true, ApplyToMembers = true)]
    public class ExporterLoader
    {
        static string PreAmble = "Exporter.dll";

        public static List<IExporter> GetExporterList()
        {
            string assInfos = "*" + PreAmble;
            List<Assembly> allAssemblies = new List<Assembly>();
            string path = Assembly.GetExecutingAssembly().Location;

            var location = Path.GetDirectoryName(path);

            foreach (string dll in Directory.GetFiles(location, assInfos))
                allAssemblies.Add(Assembly.LoadFile(dll));

            //var ass = AppDomain.CurrentDomain.GetAssemblies();

            var type = typeof(IExporter);
            var types = allAssemblies
                .SelectMany(s => s.GetTypes())
                .Where(p => type.IsAssignableFrom(p));

            List<IExporter> exporterInstances = new List<IExporter>();

            foreach(Type exporter in types)
            {
                if (!exporter.IsInterface)
                {
                    exporterInstances.Add((IExporter)Activator.CreateInstance(exporter));
                }
            }

            return exporterInstances;
        }

        //public static IExporter GetInstance(Type exporter)
        //{
        //    var type = typeof(IExporter);

        //    if (type.IsAssignableFrom(exporter))
        //    {
        //        return (IExporter)Activator.CreateInstance(exporter);
        //    }
        //    else
        //    {
        //        throw new Exception("Exportertyp is not assignable");
        //    }
        //}
    }
}
